package com.acknight.service.impl;

import com.acknight.constant.MessageConstant;
import com.acknight.constant.WXLoginConstant;
import com.acknight.dto.UserLoginDTO;
import com.acknight.entity.User;
import com.acknight.exception.LoginFailedException;
import com.acknight.mapper.UserMapper;
import com.acknight.properties.WeChatProperties;
import com.acknight.service.UserService;
import com.acknight.utils.HttpClientUtil;
import com.acknight.utils.WeChatPayUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

        String openid = getOpenId(userLoginDTO.getCode());

        // 判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 判断判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);

        // 如果是新用户自动完成注册
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        // 返回这个用户对象
        return user;
    }

    private String getOpenId(String code) {
        // 调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put(WXLoginConstant.APPID, weChatProperties.getAppid());
        map.put(WXLoginConstant.SECRET, weChatProperties.getSecret());
        map.put(WXLoginConstant.JS_CODE, code);
        map.put(WXLoginConstant.GRANT_TYPE, WXLoginConstant.GRANT_TYPE_VALUE);
        String json = HttpClientUtil.doGet(WXLoginConstant.WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString(WXLoginConstant.OPENID);

        return openid;
    }
}
